//接受web发送过来的返回事件
window.addEventListener("message", async function (event) {
    //处理页面响应的消息
    if (event.data.from === "web") {
        if (event.data.action == "localStorage_get") {
            await session.set("localStorage", event.data.data);
            // console.log("rev web response: " + JSON.stringify(event.data))
        }
        // console.log("rev web response: " + JSON.stringify(event.data))
    } else {
        // if (!!event.data && !!event.data.from && event.data.from == 'extenstion') {
        //
        // } else {
        //     try {
        //         if (event.data.data.request.api.indexOf("meiri56") == -1) {
        //             console.log(event)
        //         }
        //     } catch (e) {
        //         console.log(event)
        //     }
        // }
    }

});

//接受worker.js popup.js
chrome.runtime.onMessage.addListener(async function (request, sender, sendResponse) {
    if (request.type == 'heartBeat') {
        const pluginName = await session.get("pluginName", null)
        const serverName = await session.get("serverName", null)
        const hostCode = await session.get("hostCode", null)
        const res = await core.heartBeat(pluginName, hostCode, serverName);
        console.log('heartBeat')
        await session.set("heartBeat_time", new Date().getTime())
        let pluginRunning = await session.get("PLUGIN_RUNNING", false)
        if (pluginRunning) {
            await session.set("_TOKEN_RUNNING_", new Date().getTime())
            await getAccountAndRefresh();
        }
        sendResponse(res);
    }
    if (request.type == 'reload') {
        window.location.reload();
    }
    if (request.type == 'getAccount') {
        await getAccountAndRefresh();
        sendResponse("getAccount");
    }
    return true;
});

function webError() {
    if (document.body.innerHTML.indexOf('geo.captcha-delivery.com/captcha') != -1) {
        return true;
    }
    return false;
}
async function getAccountAndRefresh() {
    let pluginRunning = await session.get("PLUGIN_RUNNING", false)
    if (!pluginRunning) {
        return;
    }
    let last_account = await session.get("last_account", null);
    let current_step = await session.get("current_step", null);
    if (!!!current_step) {
        await session.set("current_step", "_getAccountAndRefresh");
        await session.set("has_last_step", "getNewAccount");
        const pluginName = await session.get("pluginName", null)
        const serverName = await session.get("serverName", null)
        const hostCode = await session.get("hostCode", null)
        const res = await core.getAccount(pluginName, hostCode, serverName);
        console.log("checkLogin: 账号: " + !!res ? res['username'] : null)

        await session.set("current_step_time", new Date().getTime());
        if (!!res && !!res['username']) {
            if (!!last_account && last_account == res['username']) {
                await localTimeFunction(async function () {
                    console.log('用户名一样')
                    await session.set("current_step", "_checkLogin");
                    await session.set("current_step_time", new Date().getTime());
                    window.location.reload();
                }, 4000)
                return;
            } else {
                await session.set("account", res)
                await refreshToken(res);
            }
        } else {
            //未获取到账号，重新获取
            await localTimeFunction(async function () {
                await session.remove("current_step");
                await session.remove("current_step_time");
                await getAccountAndRefresh();
            }, 4000)
        }
    }
}

async function refreshToken(res) {
    await session.set("current_step", "_refreshToken");
    await session.set("current_step_time", new Date().getTime());
    await session.set("loading", true);
    await session.set("loading_time", new Date().getTime());
    console.log("删除old:" + res['username'])
    //先删除
    let message = {"from": "extenstion", "action": "localStorage_del"};
    window.postMessage(message, "*");
    sendMsg({action: 'delCookie', domain: '.cma-cgm.com'})
    sendMsg({action: 'delCookie', domain: 'www.cma-cgm.com'})

    await localTimeFunction(async function () {
        let otherCache = !!res ? JSON.parse(res['otherCache']) : null;
        if (!!otherCache && !!otherCache['cookies'] && !!otherCache['localStorage']) {
            //再增加
            let message = {"from": "extenstion", "action": "localStorage_set", data: otherCache['localStorage']};
            window.postMessage(message, "*");
            sendMsg({action: 'setCookie', data: otherCache['cookies']})

            await localTimeFunction(async function () {
                console.log("set cookie完成")
                await session.remove("loading");
                await session.remove("loading_time");
                await session.set("has_last_step", "_login");
                await session.set("current_step", "_checkLogin");
                await session.set("current_step_time", new Date().getTime());
                window.location.reload();
            }, 2000)

        } else {
            console.log("to login")
            await session.set("current_step", "_login");
            await session.remove("login");
            await session.remove("loading");
            await session.remove("loading_time");
            await session.set("current_step_time", new Date().getTime());
            window.location.reload();
        }
    }, 2000)

}